package cn.tedu._03vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 网站限流拦截器,限制单个IP每分钟之内访问网站的次数不能超过3次
 */
@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_COUNT = 3;
    private static final int WINDOW_SIZE_SECONDS = 60;

    // {"192.168.1.11": 3, "192.168.1.22": 1, "192.168.1.33": 3}
    private final ConcurrentHashMap<String, Integer> clientCounts = new ConcurrentHashMap<>();
    // {"192.168.1.11": "2025-06-16 00:00:00",  "192.168.1.22": "2025-06-15 18:00:00"}
    private final ConcurrentHashMap<String, LocalDateTime> lastVisitTimes = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String clientIp = request.getRemoteAddr();
        LocalDateTime lastVisitTime = lastVisitTimes.get(clientIp);
        if (lastVisitTime == null || LocalDateTime.now().isAfter(lastVisitTime.plusSeconds(WINDOW_SIZE_SECONDS))){
            clientCounts.put(clientIp, 0);
            lastVisitTimes.put(clientIp, LocalDateTime.now());
        }
        //请求次数+1
        /*
            int a = clientCounts.get(clientIp)+1;
            clientCount.put(clientIp, a);
         */
        int count = clientCounts.merge(clientIp, 1, Integer::sum);
        //如果当前IP的请求次数小于3次，则放行，否则拦截
        if (count > MAX_COUNT){
            throw new RuntimeException("访问过于频繁，请稍后再试");
        }
        return true;
    }
}








